package cn.nuofankj.myblog.repository;


import cn.nuofankj.myblog.entity.Article;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import javax.transaction.Transactional;
import java.util.List;

/**
 * @author xifanxiaxue
 * @date 2020-12-20
 * @desc
 */
@Repository
@Transactional
public interface ArticleRepository extends JpaRepository<Article, Long>, JpaSpecificationExecutor<Article> {

    Article findArticleByIdAndStatus(String id, long status);

    Article findArticleById(String id);

    @Query(value = "SELECT new Article(a.id,a.title) FROM Article a WHERE a.id = ?1")
    Article findArticleTitleById(String id);

    List<Article> findByAidLessThanAndStatus(long aid, long status, Pageable pageable);

    List<Article> findByAidGreaterThanAndStatus(long aid, long status, Pageable pageable);

    List<Article> findAllByTitleContainingAndStatus(String title, long status, Pageable pageable);

    @Query(value = "SELECT new  Article(a.id,a.title,a.categoryId,a.createTime,a.deleteTime,a.updateTime,a.publishTime,a.status,a.cover,a.subMessage,a.pageview,a.isEncrypt) FROM Article a WHERE a.status = ?1")
    List<Article> findAllByStatus(long status, Pageable pageable);

    @Query(value = "SELECT new  Article(a.id,a.title,a.categoryId,a.createTime,a.deleteTime,a.updateTime,a.publishTime,a.status,a.cover,a.subMessage,a.pageview,a.isEncrypt) FROM Article a WHERE a.status = ?1 AND a.categoryId = ?2")
    List<Article> findAllByStatusAndCategoryId(long status, String categoryId, Pageable pageable);

    @Query(value = "SELECT new  Article(a.id,a.title,a.categoryId,a.createTime,a.deleteTime,a.updateTime,a.publishTime,a.status,a.cover,a.subMessage,a.pageview,a.isEncrypt) FROM Article a WHERE a.status = ?1 AND a.id != ?2")
    List<Article> findAllByStatusAndIdNotContains(long status,String id, Pageable pageable);

    @Query(value = "SELECT new  Article(a.id,a.title,a.categoryId,a.createTime,a.deleteTime,a.updateTime,a.publishTime,a.status,a.cover,a.subMessage,a.pageview,a.isEncrypt) FROM Article a WHERE a.status = ?1")
    List<Article> findAllByStatus(long status);

    @Modifying
    @Query("update Article article set article.categoryId = ?2 where article.categoryId = ?1")
    void updateArticleCatrgory(String categoryId, String newCategoryId);

    int countArticlesByStatusAndIdNotContaining(long status, String id);
}
